<?php

class Kal_Timetables_Manage_TimetablesController extends Mage_Adminhtml_Controller_action
{
	public function preDispatch()
    {
        parent::preDispatch();
    }
	
	protected function _initAction() {
		$this->loadLayout()
			->_setActiveMenu('timetables/posts');
		
		return $this;
	}   
 
	public function indexAction() {
		$this->_initAction()
			->renderLayout();
	}

	public function editAction() {
		$id     = $this->getRequest()->getParam('id');
		$model  = Mage::getModel('timetables/timetables')->load($id);

		if ($model->getId() || $id == 0) {
			$data = Mage::getSingleton('adminhtml/session')->getFormData(true);
			if (!empty($data)) {
				$model->setData($data);
			}

			Mage::register('timetables_data', $model);

			$this->loadLayout();
			$this->_setActiveMenu('timetables/posts');

			$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

			$this->_addContent($this->getLayout()->createBlock('timetables/manage_timetables_edit'))
				->_addLeft($this->getLayout()->createBlock('timetables/manage_timetables_edit_tabs'));

			$this->renderLayout();
		} else {
			Mage::getSingleton('adminhtml/session')->addError(Mage::helper('timetables')->__('Post does not exist'));
			$this->_redirect('*/*/');
		}
	}
 
	public function newAction() {
		$id     = $this->getRequest()->getParam('id');
		$model  = Mage::getModel('timetables/timetables')->load($id);

		$data = Mage::getSingleton('adminhtml/session')->getFormData(true);
		if (!empty($data)) {
			$model->setData($data);
		}

		Mage::register('timetables_data', $model);

		$this->loadLayout();
		$this->_setActiveMenu('timetables/posts');

		$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);

		$this->_addContent($this->getLayout()->createBlock('timetables/manage_timetables_edit'))
			->_addLeft($this->getLayout()->createBlock('timetables/manage_timetables_edit_tabs'));

		$this->renderLayout();
	}
 
	public function saveAction() {
		if ($data = $this->getRequest()->getPost()) {
			$data=$data['timetables'];
			//file!!!
//			print_r($data);
//			break;
			if(isset($data['nfile']['delete']) && $data['nfile']['delete']=='1'){
				if(!empty($data['nfile']['value'])){
					$path = Mage::getBaseDir('media') . DS;
					if(@unlink($path.$data['nfile']['value'])){
						$data['nfile']='';
					}
				} 	
			}
			if(isset($_FILES['nfile']['name']) && !empty($_FILES['nfile']['name'])) {
				try {
				$uploader = new Varien_File_Uploader('nfile');
			    $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); // or pdf or anything
				$uploader->setAllowRenameFiles(true);
			    // setAllowRenameFiles(true) -> move your file in a folder the magento way
			    // setAllowRenameFiles(false) -> move your file directly in the $path folder
			    $uploader->setFilesDispersion(true);
			    $path = Mage::getBaseDir('media') . DS;
			    
			    //$uploader->saveresized($path, $_FILES['nfile']['name'],100,72);
			    //$_tmp_nfilethumb = $uploader->getUploadedFileName();
			    
			    $uploader->save($path, $_FILES['nfile']['name']);
			    $_tmp_nfile = $uploader->getUploadedFileName();
			    
			    //$data['nfilethumb'] = $_tmp_nfilethumb;
			    $data['nfile'] = $_tmp_nfile;

				}catch(Exception $e) {
				
				}
			}elseif(isset($data['nfile']['value']) && !empty($data['nfile']['value'])){
				$data['nfile']=$data['nfile']['value'];
			} 	
			
			$model = Mage::getModel('timetables/post');		
			$model->setData($data)
				->setId($this->getRequest()->getParam('id'));
			$model->setCatId($data['cats'][0]);	
			
			try {
				if ($this->getRequest()->getParam('created_time') == NULL) {
					$model->setCreatedTime(now())
						->setUpdateTime(now());
				} else {
					$model->setUpdateTime(now());
				}	
				
				if ($this->getRequest()->getParam('user') == NULL) {
					$model->setUser(Mage::getSingleton('admin/session')->getUser()->getFirstname() . " " . Mage::getSingleton('admin/session')->getUser()->getLastname())
					->setUpdateUser(Mage::getSingleton('admin/session')->getUser()->getFirstname() . " " . Mage::getSingleton('admin/session')->getUser()->getLastname());
				} else {
					$model->setUpdateUser(Mage::getSingleton('admin/session')->getUser()->getFirstname() . " " . Mage::getSingleton('admin/session')->getUser()->getLastname());
				}

				if ($this->getRequest()->getParam('identifier') == NULL) {
					//$postTitle=$data['title'];
					//$postIdentifier=str_ireplace(array(" ","?"),array("-",""),strtolower($postTitle));
					$model->setIdentifier("T".uniqid());
				} 
				
				if ($data['thedate'] != "") {
					$thedate =$this->getFormattedDateString($data['thedate']);
					//print_r($thedate);
					$model->setThedate($thedate);
				} 
				
				if ($data['enddate'] != "") {
					$enddate =$this->getFormattedDateString($data['enddate']);
					//print_r($thedate);
					$model->setEnddate($enddate);
				} 
				
				if(isset($data['weekloops']) && is_array($data['weekloops']) && count($data['weekloops'])>0){
					$model->setWeekloop(implode(',',$data['weekloops']));
					//$data['post_content'].=',';
				}

				$model->save();
				Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('timetables')->__('Post was successfully saved'));
				Mage::getSingleton('adminhtml/session')->setFormData(false);

				if ($this->getRequest()->getParam('back')) {
					$this->_redirect('*/*/edit', array('id' => $model->getId()));
					return;
				}
				$this->_redirect('*/*/');
				return;
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                Mage::getSingleton('adminhtml/session')->setFormData($data);
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                return;
            }
        }
        Mage::getSingleton('adminhtml/session')->addError(Mage::helper('timetables')->__('Unable to find post to save'));
        $this->_redirect('*/*/');
	}
 
	public function deleteAction() {
		if( $this->getRequest()->getParam('id') > 0 ) {
			try {
				$model = Mage::getModel('timetables/timetables');
				 
				$model->setId($this->getRequest()->getParam('id'))
					->delete();
					 
				Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Post was successfully deleted'));
				$this->_redirect('*/*/');
			} catch (Exception $e) {
				Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
				$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
			}
		}
		$this->_redirect('*/*/');
	}

    public function massDeleteAction() {
        $timetablesIds = $this->getRequest()->getParam('timetables');
        if(!is_array($timetablesIds)) {
			Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select post(s)'));
        } else {
            try {
                foreach ($timetablesIds as $timetablesId) {
                    $timetables = Mage::getModel('timetables/timetables')->load($timetablesId);
                    $timetables->delete();
                }
                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('adminhtml')->__(
                        'Total of %d record(s) were successfully deleted', count($timetablesIds)
                    )
                );
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            }
        }
        $this->_redirect('*/*/index');
    }
	
    public function massStatusAction()
    {
        $timetablesIds = $this->getRequest()->getParam('timetables');
        if(!is_array($timetablesIds)) {
            Mage::getSingleton('adminhtml/session')->addError($this->__('Please select post(s)'));
        } else {
            try {
                foreach ($timetablesIds as $timetablesId) {
                    $timetables = Mage::getSingleton('timetables/timetables')
                        ->load($timetablesId)
                        ->setStatus($this->getRequest()->getParam('status'))
                        ->setIsMassupdate(true)
                        ->save();
                }
                $this->_getSession()->addSuccess(
                    $this->__('Total of %d record(s) were successfully updated', count($timetablesIds))
                );
            } catch (Exception $e) {
                $this->_getSession()->addError($e->getMessage());
            }
        }
        $this->_redirect('*/*/index');
    }
    
	public function getFormattedDateString($date){
		$datearray=explode('/',$date);
		if(count($datearray)==3){
			return (date('Y-m-d',strtotime($datearray[2].$datearray[1].$datearray[0])));
		}
		return '';
	}
}

class ImageResize
{

	var $_img;

	var $_imagetype;

	var $_width;

	var $_height;

	function load($img_name, $img_type=''){
		if(!empty($img_type)) $this->_imagetype = $img_type;
		else $this->_imagetype = $this->get_type($img_name);
		switch ($this->_imagetype){
			case 'gif':
				if (function_exists('imagecreatefromgif'))	$this->_img=imagecreatefromgif($img_name);
				break;
			case 'jpg':
				$this->_img=imagecreatefromjpeg($img_name);
				break;
			case 'png':
				$this->_img=imagecreatefrompng($img_name);
				break;
			default:
				$this->_img=imagecreatefromstring($img_name);
				break;
		}
		$this->getxy();
	}

	function resize($width, $height, $percent=0)
	{
		if(!is_resource($this->_img)) return false;
		/*if(empty($width) && empty($height)){
			if(empty($percent)) return false;
			else{
				$width = round($this->_width * $percent);
				$height = round($this->_height * $percent);
			}
		}elseif(empty($width) && !empty($height)){
			$width = round($height * $this->_width / $this->_height );
		}else{
			$height = round($width * $this->_height / $this->_width);
		}*/
		$tmpimg = imagecreatetruecolor($width,$height);
		if(function_exists('imagecopyresampled')) imagecopyresampled($tmpimg, $this->_img, 0, 0, 0, 0, $width, $height, $this->_width, $this->_height);
		else imagecopyresized($tmpimg, $this->_img, 0, 0, 0, 0, $width, $height, $this->_width, $this->_height);
		$this->destroy();
		$this->_img = $tmpimg;
		$this->getxy();
	}
	

	function cut($width, $height, $x=0, $y=0){
		if(!is_resource($this->_img)) return false;
		if($width > $this->_width) $width = $this->_width;
		if($height > $this->_height) $height = $this->_height;
		if($x < 0) $x = 0;
		if($y < 0) $y = 0;
		$tmpimg = imagecreatetruecolor($width,$height);
		imagecopy($tmpimg, $this->_img, 0, 0, $x, $y, $width, $height);
		$this->destroy();
		$this->_img = $tmpimg;
		$this->getxy();
	}
	
	

	function display($destroy=true)
	{
		if(!is_resource($this->_img)) return false;
		switch($this->_imagetype){
			case 'jpg':
			case 'jpeg':
				header("Content-type: image/jpeg");
				imagejpeg($this->_img);
				break;
			case 'gif':
				header("Content-type: image/gif");
				imagegif($this->_img);
				break;
			case 'png':
			default:
				header("Content-type: image/png");
				imagepng($this->_img);
				break;
		}
		if($destroy) $this->destroy();
	}

	function save($fname, $destroy=false, $type='')
	{
		if(!is_resource($this->_img)) return false;
		if(empty($type)) $type = $this->_imagetype;
		switch($type){
			case 'jpg':
			case 'jpeg':
				$ret=imagejpeg($this->_img, $fname);
				break;
			case 'gif':
				$ret=imagegif($this->_img, $fname);
				break;
			case 'png':
			default:
				$ret=imagepng($this->_img, $fname);
				break;
		}
		if($destroy) $this->destroy();
		return $ret;
	}

	function destroy()
	{
		if(is_resource($this->_img)) imagedestroy($this->_img);
	}
	

	function getxy()
	{
		if(is_resource($this->_img)){
			$this->_width = imagesx($this->_img);
			$this->_height = imagesy($this->_img);
		}
	}
	


	function get_type($img_name)
	{
		if (preg_match("/\.(jpg|jpeg|gif|png)$/i", $img_name, $matches)){
			$type = strtolower($matches[1]);
		}else{
			$type = "string";
		}
		return $type;
	}
}